<template>
  <div>
    <el-dialog
      title="添加C端用户"
      :visible.sync="dialogPipo"
      width="50%"
      :before-close="handleClose">
      <div>
       <el-form :model="ruleForm2"  :rules="rules2" ref="ruleForm2" label-width="100px" class="demo-ruleForm">
          <el-form-item label="手机" prop="userPhone">
            <el-input :disabled="editSta" v-model="ruleForm2.userPhone" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="userNick">
            <el-input  v-model="ruleForm2.userNick" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="性别" >
           <el-select v-model="ruleForm2.sex">

            <el-option v-for="(item,index) in sexs" :key="index" :label="item.label" :value="item.value"></el-option>
           </el-select>
          </el-form-item>
          <el-form-item label="头像">
            <el-row>
               <el-col :span="16">
                 <el-upload
                  style="display:inline-block"
                  :action="action"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-success="handleOK"
                  :data="postData"
                  :on-remove="handleRemove">
                  <i class="el-icon-plus"></i>
                </el-upload>
               </el-col>
              <el-col :span="8">
                <img :src="ruleForm2.userHeader" v-show="userdata" style="width:120px;height:150px;maring-left:50px" />
              </el-col>
            </el-row>
            
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm('ruleForm2')">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm2')">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import crypto from 'crypto'
import Http from '@/Http/Http'
import qnUrl from '@/Http/qiniuUrl'

export default {
  
  data() {
    
    var userPhone = (rule, value, callback) => {
      const val = value.replace(/^\s+|\s+$/g,'');
      if (value === '') {
        callback(new Error('用户名'));
      } else if (isNaN(val) && val.length != 11){
        callback(new Error('请输入 11位数字'));
      } else {
        callback();
      }
    };
    var userNick = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入昵称'));
      } else {
        callback();
      }
    };
    
    return {
      action:qnUrl,//七牛的上传地址
      tokenimgUrl:'',
      editSta:false,
      ruleForm2: {
        userPhone: '',
        sex:0,
        userHeader: '',
        userNick: ''
      },
      sexs:[
        {label:'女',value:0},
        {label:'男',value:1}
      ],
      postData:{
        token:'',
      },
      rules2: {
        userPhone: [
          { validator: userPhone, trigger: 'blur' }
        ],
        userNick: [
          { validator: userNick, trigger: 'blur' }
        ]
      }
    };
  },
  props:['dialogPipo','userdata'],
  created() {
    Http.QiniuToken({})
    .then( res => {
      
      this.postData.token = res.data.data.uptoken;
      this.tokenimgUrl = res.data.data.domain
    })
    .catch( error => {
      
    })
    if(this.userdata){
      this.ruleForm2.userPhone = this.userdata.userPhone  
      this.ruleForm2.userNick = this.userdata.userNick  
      this.ruleForm2.sex = this.userdata.userSex  
      this.ruleForm2.userHeader = this.userdata.userHeader  
      this.editSta = true
    }  
    console.dir(this.userdata)
  },
  methods:{
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
           this.userdata ? this.editCuserFun() : this.addCuserFun();
         
        } else {
          return false;
        }
      });
    },
    addCuserFun(){
      const obj = {
        "userPhone": this.ruleForm2.userPhone,
        "userNick": this.ruleForm2.userNick,
        "userSex": this.ruleForm2.sex,
        "userHeader":this.ruleForm2.userHeader
      };
      Http.addCuser(obj)
      .then( res => {
        
        if( res.data.code == 200 ) { 
          this.$message.success('用户添加成功')
          this.$emit('showFun')
        } else if (res.data.code == -1003) {
          this.$message.error(`请求失败原因：${res.data.message}`)
          setTimeout(()=>{
            this.$router.push('/')
          },2000)
        } else {
          this.$message.error('用户添加失败')              
        }
      })
      .catch( error => {
        this.$message.error('服务器请求失败')
        
      })
    },
    editCuserFun(){
      const obj = {
        "userId": this.userdata.userId,
        "userNick": this.ruleForm2.userNick,
        "userSex": this.ruleForm2.sex,
        "userHeader":this.ruleForm2.userHeader
      };
      Http.editCuser(obj)
      .then( res => {
        
        if( res.data.code == 200 ) { 
          this.$message.success('用户修改成功')
          this.$emit('showFun')
        } else if (res.data.code == -1003) {
          this.$message.error(`请求失败原因：${res.data.message}`)
          setTimeout(()=>{
            this.$router.push('/')
          },2000)
        } else {
          this.$message.error('用户修改失败')              
        }
      })
      .catch( error => {
        this.$message.error('服务器请求失败')
        
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$emit('showFun')
    },
    handleRemove(file, fileList) {
      if(userdata){
         this.ruleForm2.userHeader = userdata.userHeader;
      }
      
    },
    handlePictureCardPreview(event, file, fileList) {
    },
    handleOK(responed) {
      this.ruleForm2.userHeader = `http://${this.tokenimgUrl}/${responed.key}`
    },
    handleClose(done) {
      this.$refs["ruleForm2"].resetFields();
      this.$emit('showFun')
    }
  }
}
</script>
<style>


</style>